<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import axios from '@/utils/axios'

const activeTab = ref(1) // 将默认值从 0 改为 1，表示默认选中"推荐"标签
const router = useRouter()
const route = useRoute()

// 帖子数据
const posts = ref([])

const onClickSearch = () => {
  router.push('/search');
}

const onClickMessage = () => {
  router.push('/notifications' );
}

// 跳转到发布页面
const goToPost = () => {
  router.push('/postfs')
}

// 跳转到评论页面
const goToComment = (postId: number) => {
  router.push({
    path: '/comment',
    query: { postId: postId.toString() }
  })
}

// 跳转到关注页面
const goToFollow = () => {
  router.push('/follow')
}

// 减肥广场功能模块
const fitnessModules = [
  {
    id: 1,
    icon: 'aim',
    title: '健身教程'
  },
  {
    id: 2,
    icon: 'bookmark',
    title: '减肥经验'
  },
  {
    id: 3,
    icon: 'clock',
    title: '打卡日记'
  },
  {
    id: 4,
    icon: 'question',
    title: '问答交流'
  },
  {
    id: 5,
    icon: 'gift',
    title: '饮食分享'
  }
]

// 处理模块点击事件
const handleModuleClick = (module: any) => {
  showToast(`点击了${module.title}`)
  if (module.id === 1) {
    router.push('/tutorial')
  }
  if (module.id === 2) {
    router.push('/experience')
  }
  // 如果点击的是打卡日记，则跳转到打卡页面
  if (module.id === 3) {
    router.push('/clock-in')
  }
  if (module.id === 4) {
    router.push('/qa')
  }
  if (module.id === 5) {
    router.push('/diet')
  }
}

// 获取帖子数据
const fetchPosts = async (typeId = 0) => {
  try {
    console.log('开始获取帖子数据，typeId:', typeId);
    const response = await axios.get('/api/post/page', {
      params: {
        pageNum: 1,
        pageSize: 10,
        typeId: typeId,
      }
    })

    console.log('收到响应:', response);

    // 由于axios拦截器返回的是response.data，所以直接检查response即可
    if (response && response.hasOwnProperty('code')) {
      if (response.code === 200) {
        // 检查data和records字段
        if (response.data && response.data.records) {
          console.log('帖子记录:', response.data.records);
          posts.value = response.data.records.map((post: any) => {
            // 确保必要的字段存在
            return {
              ...post,
              likes: post.likes !== undefined ? post.likes : 0,
              commentCount: post.commentCount !== undefined ? post.commentCount : 0,
              users: post.users || {
                userId: post.userId || 0,
                nickname: '匿名用户',
                avatar: '',
                gender: '未知',
                height: 0,
                targetWeight: 0
              }
            }
          })
          console.log('成功设置帖子数据:', posts.value);
        } else {
          console.error('数据结构不正确，缺少records字段:', response);
          showToast('数据格式错误');
        }
      } else {
        console.error('服务器返回错误码:', response.code, response.msg);
        showToast(response.msg || '获取数据失败');
      }
    } else {
      console.error('响应缺少code字段:', response);
      showToast('服务器响应格式错误');
    }
  } catch (error) {
    console.error('获取帖子数据时发生错误:', error);
    if (error.response) {
      console.error('错误响应:', error.response);
      showToast(`服务器错误: ${error.response.status}`);
    } else if (error.request) {
      console.error('无响应:', error.request);
      showToast('服务器无响应');
    } else {
      console.error('请求错误:', error.message);
      showToast('请求失败');
    }
  }
}

// 格式化时间显示
const formatTime = (timeString: string) => {
  // 添加安全检查
  if (!timeString) return ''

  const date = new Date(timeString)
  // 检查日期是否有效
  if (isNaN(date.getTime())) return ''

  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const minutes = Math.floor(diff / (1000 * 60))

  if (minutes < 1) {
    return '刚刚'
  } else if (minutes < 60) {
    return `${minutes}分钟前`
  } else if (minutes < 24 * 60) {
    const hours = Math.floor(minutes / 60)
    return `${hours}小时前`
  } else {
    const days = Math.floor(minutes / (24 * 60))
    return `${days}天前`
  }
}

// 点赞功能
const handleLike = async (post: any) => {
  try {
    const token = sessionStorage.getItem("token")

    // 检查是否有token
    if (!token) {
      showToast('请先登录')
      return
    }

    const response = await axios.get('/api/post/likes', {
      params: {
        postId: post.postId
      },
      headers: {
        'token': token
      }
    })

    // 由于axios拦截器返回的是response.data，所以直接检查response即可
    if (response.code === 200) {
      post.likes = response.data.likes
      post.userLiked = response.data.isLiked
      showToast(response.msg)
    } else {
      showToast(response.msg || '操作失败')
    }
  } catch (error) {
    showToast('网络错误')
    console.error(error)
  }
}

// 监听标签页变化
watch(activeTab, (newVal) => {
  if (newVal === 0) {
    // 当切换到关注标签时，跳转到关注页面
    goToFollow();
  }
})

// 监听路由变化
watch(
  () => route.path,
  (newPath) => {
    let typeId = 0;
    // 根据路由路径设置对应的 typeId
    if (newPath === '/clock-in') {
      typeId = 4; // 根据内存信息，ClockIn.vue 使用 typeId=4 表示'每日打卡'模块
    } else if (newPath === '/tutorial') {
      typeId = 1; // 健身教程模块ID
    } else if (newPath === '/experience') {
      typeId = 2; // 减肥经验模块ID
    } else if (newPath === '/qa') {
      typeId = 4; // 问答交流模块ID（与打卡日记相同）
    } else if (newPath === '/diet') {
      typeId = 5; // 饮食分享模块ID
    }
    
    fetchPosts(typeId);
  }
)

onMounted(() => {
  fetchPosts()
})
</script>

<template>
  <div>
    <!-- 顶部导航栏 -->
    <div class="top-nav-bar">
      <div class="nav-left">
        <van-tabs v-model:active="activeTab" class="custom-tabs" line-height="0">
          <van-tab title="关注">
            <template #title>
              <div @click="goToFollow">关注</div>
            </template>
          </van-tab>
          <van-tab title="推荐" />
          <van-tab title="评分榜" />
        </van-tabs>
      </div>
      <div class="nav-right">
        <van-icon name="search" size="18" class="nav-icon" @click="onClickSearch" />
        <van-icon name="envelop-o" size="18" class="nav-icon" @click="onClickMessage" />
      </div>
    </div>

    <!-- 页面内容 -->
    <div class="page-content">
      <!-- 减肥广场框架 -->
      <div class="fitness-square">
        <h2 class="section-title">减肥广场</h2>
        <div class="modules-container">
          <div class="modules-flex">
            <div
              v-for="module in fitnessModules"
              :key="module.id"
              class="module-item"
              @click="handleModuleClick(module)"
            >
              <van-icon :name="module.icon" size="24" class="module-icon" />
              <div class="module-title">{{ module.title }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 每日打卡帖子内容 -->
      <div class="posts-section">
        <h3 class="posts-title">热门帖子</h3>
        <div v-for="post in posts" :key="post.postId || post.id" class="post-item">
          <div class="post-header">
            <van-image
              :src="post.users?.avatar || 'https://img.yzcdn.cn/vant/cat.jpeg'"
              round
              width="40"
              height="40"
              class="user-avatar"
            />
            <div class="user-info">
              <div class="user-name">{{ post.users?.nickname || '匿名用户' }}</div>
              <div class="user-meta">
                <span class="gender">{{ post.users?.gender || '未知' }}</span>
                <span class="height">{{ post.users?.height || 0 }}cm</span>
                <span class="weight">目标: {{ post.users?.targetWeight || 0 }}kg</span>
              </div>
            </div>
            <div class="post-time">{{ formatTime(post.postTime) }}</div>
          </div>

          <div class="post-content">
            {{ post.content || '' }}
          </div>

          <!-- 图片展示 -->
          <div v-if="post.images" class="post-images">
            <div
              v-for="(image, index) in post.images.split(',')"
              :key="index"
              class="image-container"
            >
              <van-image
                :src="image"
                width="100%"
                height="150"
                fit="cover"
                radius="8"
              />
            </div>
          </div>

          <!-- 点赞和评论 -->
          <div class="post-actions">
            <div class="like-section" @click="handleLike(post)">
              <van-icon
                :name="post.userLiked ? 'like' : 'like-o'"
                :color="post.userLiked ? '#1989fa' : '#ccc'"
                size="18"
              />
              <span :class="{ liked: post.userLiked }">{{ post.likes || 0 }}</span>
            </div>
            <div class="comment-section" @click="goToComment(post.postId)">
              <van-icon
                name="comment-o"
                color="#ccc"
                size="18"
              />
              <span>{{ post.commentCount || 0 }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 发布按钮 -->
    <div class="fab-button" @click="goToPost">
      <van-icon name="edit" size="24" color="#fff" />
    </div>

    <!-- 底部导航栏占位 -->
    <div class="bottom-placeholder"></div>
  </div>
</template>

<style scoped>
.top-nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  padding: 0 16px;
  box-sizing: border-box;
  border-bottom: 1px solid #ebedf0;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  z-index: 999;
}

.nav-left {
  flex: 1;
  overflow: hidden;
}

.nav-right {
  display: flex;
  align-items: center;
  flex-shrink: 0;
  margin-left: 10px;
}

.nav-icon {
  margin-left: 20px;
  cursor: pointer;
  color: #323233;
}

.custom-tabs {
  height: 100%;
}

:deep(.van-tabs) {
  height: 100%;
}

:deep(.van-tabs__wrap) {
  height: 100%;
}

:deep(.van-tab) {
  font-size: 16px;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 12px;
  white-space: nowrap;
  color: #323233;
}

:deep(.van-tab--active) {
  color: #323233;
  font-weight: 600;
}

:deep(.van-tabs__line) {
  background-color: #323233;
}

.page-content {
  padding: 60px 16px 16px;
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #333;
}

.modules-container {
  width: 100%;
  overflow-x: auto;
  padding: 10px 0;
}

.modules-flex {
  display: flex;
  gap: 20px;
  min-width: max-content;
  padding: 0 10px;
}

.module-item {
  flex: 0 0 auto;
  width: 70px;
  background: #fff;
  border-radius: 10px;
  padding: 15px 5px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #ebedf0;
}

.module-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  border-color: #ddd;
}

.module-icon {
  margin-bottom: 8px;
  color: #323233;
}

.module-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
}

/* 发布按钮样式 */
.fab-button {
  position: fixed;
  bottom: 70px; /* 调整位置在底部导航栏上方 */
  right: 20px;
  width: 56px;
  height: 56px;
  background-color: #1989fa;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(25, 137, 250, 0.4);
  cursor: pointer;
  z-index: 1000;
  transition: all 0.3s;
}

.fab-button:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(25, 137, 250, 0.5);
}

/* 底部占位元素 */
.bottom-placeholder {
  height: 60px; /* 为底部导航栏留出空间 */
}

/* 帖子内容样式 */
.posts-section {
  margin-top: 30px;
}

.posts-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #333;
}

.post-item {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.user-avatar {
  margin-right: 12px;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.user-meta {
  display: flex;
  font-size: 12px;
  color: #999;
}

.user-meta span {
  margin-right: 10px;
}

.post-time {
  font-size: 12px;
  color: #999;
}

.post-content {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
  margin-bottom: 12px;
}

.post-images {
  display: flex;
  overflow-x: auto;
  gap: 10px;
  padding: 5px 0;
  margin-bottom: 12px;
}

.image-container {
  flex: 0 0 auto;
  width: 150px;
}

.post-actions {
  display: flex;
  gap: 20px;
}

.like-section, .comment-section {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.like-section span, .comment-section span {
  margin-left: 5px;
  font-size: 14px;
  color: #999;
}

.like-section .liked {
  color: #1989fa;
}
</style>